package com.ruoyi.custservice.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.mapper.BankErrorMapper;
import com.ruoyi.bizsys.service.*;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.bizsys.vo.LoanDeferredOrderVo;
import com.ruoyi.bizsys.vo.MonnifyReservedAccount;
import com.ruoyi.bizsys.vo.WalletFlowVo;
import com.ruoyi.bizsys.vo.WalletOrderVo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.*;
import com.ruoyi.custservice.domain.*;
import com.ruoyi.custservice.service.CustomerService;
import com.ruoyi.sms.common.SmsUtil;
import com.ruoyi.sms.config.SmsSendConfig;
import com.ruoyi.sms.domain.SmsSendData;
import com.ruoyi.sms.service.ISmsService;
import com.ruoyi.sms.util.SmsSignUtil;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.util.business.Constants;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.ruoyi.common.constant.ApplyConstants.APPLY_STATE_REJECT;

/**
 * 借款申请Controller
 *
 * @author african-loan
 * @date 2021-04-15
 */
@RestController
@RequestMapping("/business/customer")
public class CustomerController extends BaseController {

	@Autowired
	private CustomerService customerService;

	@Autowired
	private ILoanIouService loanIouService;

	@Autowired
	private ILoanOverflowService loanOverflowService;

	@Autowired
	BankErrorMapper bankErrorMapper;

	@Autowired
	ISysConfigService sysConfigService;

	@Autowired
	IWalletAmountService walletAmountService;

	@Autowired
	private IWalletFlowService walletFlowService;

	@Autowired
	private IWalletOrderService walletOrderService;

	@Autowired
	SmsSendConfig smsSendConfig;
	private SmsSignUtil smsSignUtil = new SmsSignUtil();

	/**
	 * 短信发送工具类
	 */
	private SmsUtil smsUtil = new SmsUtil();

	@Autowired
	private ISmsService smsService;

	private List<BankError> bankErrorList = null;

	@Autowired
	private IExtIdentityResultService iExtIdentityResultService;

	@Autowired
	private IRealNameAuthService realNameAuthService;

	@Autowired
	private IAppUserService appUserService;


	/**
	 * 查询是否有数据
	 */
	@GetMapping(value = "/findcount/{custNo}")
	public AjaxResult findCount(@PathVariable("custNo") String custNo){
		IsExistRsp  existRsp =  customerService.selectIsExist(custNo);
		return AjaxResult.success(existRsp);
	}

	/**
	 * 查询客户列表
	 *
	 * @param customer
	 * @return
	 */
	@PreAuthorize("@ss.hasPermi('business:customer:list')")
	@GetMapping(value = "/listcustomer")
	public TableDataInfo listcustomer(CustomerRsp customer) {
		startPage();
		return getDataTable(customerService.selectCustomerList(customer));
	}

	/**
	 * 查询客户详情
	 *
	 * @param custNo
	 * @return
	 */
	@PreAuthorize("@ss.hasPermi('business:customer:detail')")
	@GetMapping(value = "/customer/detail/{custNo}")
	public AjaxResult getCustomerInfo(@PathVariable("custNo") String custNo) {
		CustomerRsp customer = customerService.selectCustomerByCustNo(custNo);
		DecimalFormat df2 = new DecimalFormat("#,###");//千分位格式化
		if (null == customer){
			return AjaxResult.success(customer);
		}
		// 如果查询的邀请人邀请码存在，查出这个邀请码是否有效
		if(StringUtils.isNotEmpty(customer.getRecommendCode())){
			String inviteStatus = customerService.selectInviteStatus(customer.getRecommendCode());
			customer.setInviteCodeStatus(inviteStatus);
		}

		// 查询出 用户当前用户的现在和之前的信用评级
		ArrayList<RuleOut> creditRatings =customerService.selectNowAndBeforeCreditRating(custNo);
		if(CollectionUtils.isNotEmpty(creditRatings)){
			if(creditRatings.size()>=1){
				if(null!=creditRatings.get(0)){
					customer.setNowCreditRating(creditRatings.get(0).getCreditRating());
				}
			}
			if(creditRatings.size()==2){
				if(null!=creditRatings.get(1)){
					customer.setBeforeCreditRating(creditRatings.get(1).getCreditRating());
				}
			}
		}
		if(null == customer.getCreditApplayCreatetime() && !"".equals(customer.getCreditApplayCreatetime())){
			customer.setRecentCreditTime(customer.getCreditApplayCreatetime());
		}
		if(StringUtils.isNotEmpty(customer.getLoanStatus())){
			customer.setLoanStatuss(getLoanStatus(customer.getLoanStatus()));
		}
		if(StringUtils.isNotEmpty(customer.getApplyStatus())){
			customer.setApplyStatuss(getLoanStatus(customer.getApplyStatus()));
		}
		customer.setBalance(getUsableAmount(custNo));
		customer.setWalletAmount(walletAmountService.selectWalletAmount(custNo).setScale(2, BigDecimal.ROUND_UP));
		if(StringUtils.isNotEmpty(customer.getState())){
			if (customer.getState().equals("Rejested")){
				long creditApplayDay = DateUtils.getDatePoorDay(null != customer.getCreditApplayCreatetime()?
						DateUtils.addDays(customer.getCreditApplayCreatetime(),31):new Date(), new Date());
				customer.setNextCredit(creditApplayDay > 0 && creditApplayDay <= 30 ? "Note：Users can try again after " +creditApplayDay+ " days" :customer.getState());
			}else if (customer.getState().equals("Delay")){
				long loanOrderDay = DateUtils.getDatePoorDay(null != customer.getLoanOrderCreatetime()?DateUtils.addDays(customer.getLoanOrderCreatetime(),8):new Date(), new Date());
				customer.setNextCredit(loanOrderDay > 0 && loanOrderDay <= 7 ?"Note：Users can try again after " +loanOrderDay+ " days" :customer.getState());
			}else {
				customer.setNextCredit(customer.getState());
			}
		}

		//号码转码加密
		if(StringUtils.isNotEmpty(customer.getEncryptMobile())){
			customer.setEncryptMobile(PhoneCompressUtil.digit10to16(customer.getEncryptMobile()));

		}
		return AjaxResult.success(customer);
	}

	//计算balance
	public BigDecimal getUsableAmount(String custNo) {
		BigDecimal balance = new BigDecimal(0);
		if (StringUtils.isNotEmpty(custNo)){
			LoanOverflow loanOverflow = new LoanOverflow();
			loanOverflow.setCustNo(custNo);
			List<LoanOverflow> loanOverflowList = loanOverflowService.selectLoanOverflowList(loanOverflow);
			if (ObjectUtil.isNotEmpty(loanOverflowList)) {
				for (LoanOverflow loanOverflowInfo : loanOverflowList) {
					balance = balance.add(loanOverflowInfo.getChangeAmount());
				}
			}
		}
		return balance;
	}

	/**
	 * 查询提现记录
	 *
	 * @param loanOrder
	 * @return
	 */
	@Log(title = "查询提现记录")
	@PreAuthorize("@ss.hasPermi('business:loan:loanlist')")
	@GetMapping(value = "/loanlist")
	public TableDataInfo loanlist(LoanOrderVO loanOrder) {
		startPage();
		List<LoanOrderVO> orderList = customerService.selectLoanOrderList(loanOrder);
		CustomerRsp peopleInfo = getPeopleInfo(loanOrder.getCustNo());
		String clientName = "";
		if(null != peopleInfo){
			clientName = peopleInfo.getClientName();
		}

		if (CollectionUtils.isNotEmpty(orderList)) {
			for (LoanOrderVO customerRsp : orderList) {
				if (null != customerRsp && null !=customerRsp.getIouStatus()) {
					customerRsp.setState(getIouStatus(String.valueOf(customerRsp.getIouStatus())));
				}else  if (null != customerRsp && null !=customerRsp.getLoanStatus()) {
					customerRsp.setState(getLoanOrderStatus(String.valueOf(customerRsp.getLoanStatus())));
				}
				customerRsp.setLoanAmt(customerRsp.getLoanAmt().setScale(2, BigDecimal.ROUND_UP));
				// 根据具体的失败状态，匹配相应的回复信息
				matchingWithdrawal(clientName, customerRsp);
			}
		}
		return getDataTable(orderList);
	}
	// 提现失败展示原因       根据具体的失败状态，匹配相应的回复信息
	private void matchingWithdrawal(String clientName, LoanOrderVO customerRsp) {
		if("Failure".equals(customerRsp.getState())){
			if( Constants.LOAN_STATUS_1o_CANCEL == customerRsp.getLoanStatus()){
				customerRsp.setBehavior("Failed due to system issues");
				customerRsp.setDictate("Dear " +
						clientName +
						", your " +
						customerRsp.getLoanAmt() +
						" withdrawal application was" +
						" canceled or delayed due to a system issue. Please upgrade the app to the latest " +
						"version and submit the withdrawal application again. We are deeply sorry for the inconvenience.");
			}
			if( Constants.LOAN_STATUS_8_CLOSE == customerRsp.getLoanStatus()){
				customerRsp.setBehavior("Failed due to system issues");
				customerRsp.setDictate("Dear " +
						clientName +
						", your " +
						customerRsp.getLoanAmt() +
						" withdrawal application was canceled or delayed due to a system issue. Please upgrade the app to the latest version and submit the withdrawal application again. We are deeply sorry for the inconvenience.");
			}
			if( Constants.LOAN_STATUS_5_LOAN_FAILED == customerRsp.getLoanStatus()){
				customerRsp.setBehavior("Failed due to system issues");
				customerRsp.setDictate("Dear " +
						clientName +
						", your " +
						customerRsp.getLoanAmt() +
						" withdrawal application was canceled or delayed due to a system issue. Please upgrade the app to the latest version and submit the withdrawal application again. We are deeply sorry for the inconvenience.");
			}
			if( Constants.LOAN_STATUS_2_INSUFFICIENT_ACCOUNT_BALANCE == customerRsp.getLoanStatus()){
				customerRsp.setBehavior("Failed due to system issues");
				customerRsp.setDictate("Dear " +
						clientName +
						", your " +
						customerRsp.getLoanAmt() +
						" withdrawal application was canceled or delayed due to a system issue. Please upgrade the app to the latest version and submit the withdrawal application again. We are deeply sorry for the inconvenience.");
			}
			if( Constants.LOAN_STATUS_0_APPROVE_REFUSED == customerRsp.getLoanStatus()){
				customerRsp.setBehavior("Current credit history is not eligible for withdrawal");
				customerRsp.setDictate("Dear " +
						clientName +
						", unfortunately, your withdrawal request has been declined due to your current credit history does not meet our loan requirements. We truly apologize for bringing you an unpleasant experience. Please keep a good credit history and come back to apply after the stipulated time given. Thanks");
			}
		}
	}

	// 获取全名
	private CustomerRsp getPeopleInfo(String custNo) {
		CustomerRsp peopleInfo = customerService.findClientNameByCustNo(custNo);
		if(null != peopleInfo){
			return peopleInfo;
		}
		return null;
	}


	/**
	 * 查询提现详情
	 *
	 * @param id 提现申请id
	 * @return
	 */
	@Log(title = "查询提现记录详情")
	@PreAuthorize("@ss.hasPermi('business:loanIou:loandetail')")
	@GetMapping(value = "/loanIou/detail/{id}")
	public AjaxResult getLoanIouInfo(@PathVariable("id") Long id) {
		LoanIouRsp res = new LoanIouRsp();
		DecimalFormat df2 = new DecimalFormat("#,###");//千分位格式化
		// 查询出来提现信息
		LoanOrderVO loanOrder = customerService.selectLoanOrderInfo(id);
		if (null == loanOrder) {
			return AjaxResult.success(res);
		}
		res.setLoanAmount(loanOrder.getLoanAmt().setScale(2, BigDecimal.ROUND_UP));
		res.setApplicationTime(loanOrder.getCreateTime());
		res.setAccountNumber(loanOrder.getAccountNumber());
		res.setLoanDuration(loanOrder.getPeriodNum());
		res.setUnit(loanOrder.getUnit());
		res.setRepaymentTime(loanOrder.getRepayDate());
		res.setRepaymentAmount(loanOrder.getTotalAmt().setScale(2, BigDecimal.ROUND_UP));
		res.setPaymentTime(loanOrder.getPaymentTime());
		if (null != loanOrder.getLoanStatus()) {
			res.setLoanStatuss(getLoanStatus(String.valueOf(loanOrder.getLoanStatus())));
		}

		//申请人全名
		res.setApplicant(loanOrder.getApplicant());

		//提现成功
		if (loanOrder.getLoanStatus() == Constants.LOAN_STATUS_4_LOAN_SUCCESS) {
			//查询是否已经还款
			LoanIou loanIou = new LoanIou();
			loanIou.setLoanSerialNo(loanOrder.getLoanSerialNo());
			List<LoanIou> iouList = loanIouService.selectLoanIouList(loanIou);
			if (CollectionUtils.isEmpty(iouList)){
				return AjaxResult.success(res);
			}
			LoanIou iou = iouList.get(0);
			BigDecimal repaidPrincipal = iou.getRepaidPrincipal();//已还本金
			BigDecimal repaidServiceFee = iou.getRepaidServiceFee();//已还服务费
			BigDecimal repaidInterest = iou.getRepaidInterest();//已还总利息
			BigDecimal repaidLateFee = iou.getRepaidLateFee();//已还滞纳金
			BigDecimal feeRemissionAmt = iou.getFeeRemissionAmt();//减免金额

			BigDecimal loanPrincipal = iou.getLoanPrincipal();//放款本金
			BigDecimal serviceFee = iou.getServiceFee();//服务费
			BigDecimal loanInterest = iou.getLoanInterest();//总利息
			BigDecimal lateFee = iou.getLateFee();//滞纳金
			BigDecimal overdueAmount = iou.getOverdueAmount();//逾期金额

			BigDecimal addTotal = LoanIou.calculationOverdueAmount(iou);

			BigDecimal principal = loanPrincipal.add(serviceFee).add(loanInterest)
					.add(lateFee).add(overdueAmount)
					.subtract(repaidPrincipal).subtract(repaidServiceFee)
					.subtract(repaidInterest).subtract(repaidLateFee)
					.subtract(feeRemissionAmt);
			//剩余应还
			res.setRemainingRepayments(addTotal.setScale(2, BigDecimal.ROUND_UP));
			//剩余应还明细
			res.setRemainingLoanPrincipal(loanPrincipal.subtract(iou.getRepaidPrincipal()==null?BigDecimal.ZERO:iou.getRepaidPrincipal()).setScale(2, BigDecimal.ROUND_UP));
			res.setRemainingInterest(loanInterest.subtract(iou.getRepaidInterest()==null?BigDecimal.ZERO:iou.getRepaidInterest()).setScale(2, BigDecimal.ROUND_UP));
			res.setRemainingServiceFee(serviceFee.subtract(iou.getRepaidServiceFee()==null?BigDecimal.ZERO:iou.getRepaidServiceFee()).setScale(2, BigDecimal.ROUND_UP));
			res.setRemainingLateFee(lateFee.subtract(iou.getRepaidLateFee()==null?BigDecimal.ZERO:iou.getRepaidLateFee()).setScale(2, BigDecimal.ROUND_UP));

			//总应还明细
			res.setPrincipal(iou.getLoanPrincipal().setScale(2, BigDecimal.ROUND_UP));
			res.setInterest(iou.getLoanInterest().setScale(2, BigDecimal.ROUND_UP));
			res.setServiceFee(iou.getServiceFee().setScale(2, BigDecimal.ROUND_UP));
			res.setPenalty(iou.getLateFee().setScale(2, BigDecimal.ROUND_UP));
			res.setTransationFree("FREE");
			res.setLoanSerialNo(iou.getLoanSerialNo());
			//总计
			res.setRepaymentAmount(loanPrincipal.add(serviceFee).add(loanInterest)
					.add(lateFee).setScale(2, BigDecimal.ROUND_UP));
			res.setCoupon("NO Discount Coupon");
			//延期还款日
			res.setNewRepaymentDate(StringUtils.isEmpty(iou.getDeferredRepayDate()) ? "" : iou.getDeferredRepayDate());
		}

		return AjaxResult.success(res);
	}

	public String getLoanOrderStatus(String key) {
		Map<String, String> stringMap = new HashMap<>();
		stringMap.put("0", "Failure");
		stringMap.put("1", "Processing");
		stringMap.put("2", "Failure");
		stringMap.put("3", "Processing");
		stringMap.put("4", "Outstanding");
		stringMap.put("5", "Failure");
		stringMap.put("6", "Processing");
		stringMap.put("7", "Processing");
		stringMap.put("9", "Processing");
		stringMap.put("10", "Failure");
		return stringMap.get(key);
	}

	public String getIouStatus(String key) {
		Map<String, String> stringMap = new HashMap<>();
		stringMap.put("0", "Outstanding");
		stringMap.put("1", "Finish");
		stringMap.put("2", "Overdue");
		return stringMap.get(key);
	}

	public String getLoanStatus(String key) {
		Map<String, String> stringMap = new HashMap<>();
		stringMap.put("0", "审批拒绝");
		stringMap.put("1", "审批通过");
		stringMap.put("9", "审批中");
		stringMap.put("11", "信息待补充（完成授信申请1）");
		return stringMap.get(key);
	}

	/**
	 * 查询银行账户号号和银行名称
	 */
	@GetMapping(value = "/listbank")
	public TableDataInfo listBank(BankRsp bankRsp) {
		startPage();
		String custNo = bankRsp.getCustNo();
		List<BankRsp> bankByCustNo = customerService.findBankByCustNo(custNo);
		return getDataTable(bankByCustNo);
	}

	/**
	 * 查询用户的绑卡记录
	 */
	@GetMapping(value = "/findbanklistlog")
	public TableDataInfo findBankListLog(BindBankLogRsp bindBankLogRsp) {
		startPage();
		String custNo = bindBankLogRsp.getCustNo();
		List<BindBankLogRsp> bindBankLogList = customerService.findBindBankLogByCustNo(custNo);
		// 查询出所有的绑卡错误信息remark
		if(null==bankErrorList){
			bankErrorList = bankErrorMapper.selectList();
		}
		if(CollectionUtils.isEmpty(bindBankLogList)){
			return getDataTable(bindBankLogList);
		}
		for (BindBankLogRsp bankLogRsp: bindBankLogList) {
			// 失效卡(绑卡日志表成功，绑卡表中失效状态)，展示原因
			if(Constants.BIND_CARD_TRANS_SUCCESS.equals(bankLogRsp.getTransStatus()) && "0".equals(bankLogRsp.getCardStatus())){
				bankLogRsp.setRemark(bankLogRsp.getCardMarket());
				bankLogRsp.setBehavior("Bank card  invalid, please change the card and try again");
				bankLogRsp.setDictate("Try again with different card");
			}
			// 绑卡失败，展示原因
			if(Constants.BIND_CARD_TRANS_FAILED.equals(bankLogRsp.getTransStatus())){
				for (BankError bankError:bankErrorList) {
					if(StringUtils.isNotEmpty(bankError.getRemark())){
						if(bankError.getRemark().equals(bankLogRsp.getBindCardMarket())){
							bankLogRsp.setRemark(bankError.getRemark());
							bankLogRsp.setBehavior(bankError.getPrompt());
							bankLogRsp.setDictate(bankError.getOperationGuide());
						}
					}
				}
			}

		}
		return getDataTable(bindBankLogList);
	}

	/**
	 * 根据借据流水号查询出所有的还款记录
	 */
	@GetMapping(value = "/findrepaymentorderbyloanserialno/{loanSerialNo}")
	public AjaxResult findRepaymentOrderByLoanSerialNo(@PathVariable("loanSerialNo") String loanSerialNo) {
		startPage();
		JSONObject jsonObject = new JSONObject();
		// 根据借据流水号查询出所有的还款记录
		List<RepaymentOrderRsp> repaymentOrder = customerService.findRepaymentOrderByLoanSerialNo(loanSerialNo);
		if(CollectionUtils.isEmpty(repaymentOrder)){
			return AjaxResult.success(repaymentOrder);
		}
		// 查询出来所有的还款金额
		BigDecimal allRepaid =  customerService.findAllRepaid(loanSerialNo);
		jsonObject.put("AllRepaid",allRepaid);
		jsonObject.put("data",repaymentOrder);
		return AjaxResult.success(jsonObject);
	}

	/**
	 * custome_info页面的实名认证记录，
	 */
	@Log(title = "customer_info页面 用户的实名认证日志")
	@GetMapping("/findlist/bycustno")
	public TableDataInfo findListByCustNo(RealNameAuthLog realNameAuth){
		startPage();
		String custNo = realNameAuth.getCustNo();
		// 根据custNo查询出实名认证列表
		List<RealNameAuthLogRsp> realNameAuthLogList = customerService.findListByCustNo(custNo);
		if(CollectionUtils.isEmpty(realNameAuthLogList)){
			return getDataTable(realNameAuthLogList);
		}
		CustomerRsp peopleInfo = getPeopleInfo(custNo);
		String clientName = "";
		if(null != peopleInfo){
			clientName = peopleInfo.getClientName();
		}
		for (RealNameAuthLogRsp realNameAuthLog: realNameAuthLogList) {
			// 查询实名认证表中是否有数据，有证明实名成功
			selectRealNameAuthIsExist(custNo, realNameAuthLog);
			// failure 代表状态为0 失败的状态，细化信息匹配客户话术
			matchingScript(realNameAuthLog,clientName);
		}
		return getDataTable(realNameAuthLogList);
	}

	private boolean checkMatchingScript() {
		String value = sysConfigService.selectConfigByKey("matching-script");
		if("true".equals(value)){
			return true;
		}
		return false;
	}

	// 查询实名认证表中是否有数据，有证明实名成功
	private void selectRealNameAuthIsExist(String custNo, RealNameAuthLogRsp realNameAuthLog) {
		if("Succeed".equals(realNameAuthLog.getState())||StringUtils.isEmpty(realNameAuthLog.getErrorMsg())||"Verification phone number failed.".equals(realNameAuthLog.getErrorMsg())){
			int realNameAuthRspCount =  customerService.selectRealNameAuth(custNo);
			if(realNameAuthRspCount == 0){
				realNameAuthLog.setState("Failure");
			}
		}
		if("Succeed".equals(realNameAuthLog.getState()) && StringUtils.isNotEmpty(realNameAuthLog.getErrorMsg()) && !"Verification phone number failed.".equals(realNameAuthLog.getErrorMsg())){
			realNameAuthLog.setState("Failure");
		}
	}

	// 细化实名认证错误的信息匹配客服话术
	private void matchingScript(RealNameAuthLogRsp realNameAuthLog,String clientName) {
		if("Failure".equals(realNameAuthLog.getState()) ){
			//查一下bvnPhone 脱敏显示后4位
			String identityPhones = iExtIdentityResultService.getIdentityDesensitizePhones(realNameAuthLog.getId());
			realNameAuthLog.setBvnPhone(identityPhones);
			if("Birthday or mobile phone number is empty, real name failed!".equals(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("BVN or BVN number not found");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Please check your account is bound with your BVN. You may have to visit the bank to update the relevant profile and try again. If you are willing to visit the bank and update your bank account, please press the button to allow us to put you in the record. Feel free to contact our In-App customer service once the update is completed.");
				}
			}
			if("Gps check Failed.".equals(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("Unavailable");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Our service is unavailable for you currently. Sorry for bringing you an unpleasant experience.");
				}
			}
			if("Real name check failed,Over Age.".equals(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("Unavailable");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Our service is unavailable for you currently. Sorry for bringing you an unpleasant experience.");
				}
			}
			if("Real name check failed,By Okra-Verification.".equals(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("ACCOUNT and BVN do not match");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Please check your account is bound with your BVN. You may have to visit the bank to update the relevant profile and try again. If you are willing to visit the bank and update your bank account, please press the button to allow us to put you in the record. Feel free to contact our In-App customer service once the update is completed.");
				}
			}
			if(StringUtils.isEmpty(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("BVN-Bound number did not receive OTP");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Please check the BVN-bound phone number is normally using; if not, please visit your bank to update the BVN-bound phone number. If you are willing to visit the bank and update your phone number, please press the button to allow us to put you in the record. Feel free to contact our In-App customer service once the update is completed.");
				}
			}
			if("Real name check failed (by birthday). ".equals(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("The birthday information filled in by the user does not match the birthday information reserved by BVN");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Please double-check with the bank before you fill in the birthday information and confirm that the birthday you filled in is consistent with the information submitted by the bank.");
				}
			}
			if("Verification phone number failed.".equals(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("Check that the MOBILE number and BVN number are accurate");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Firstly, check the BVN-bound phone number is normally using and accurate; if not, please visit your bank to double-check the correct information and update the BVN-bound phone number if it is incorrect. If you are willing to visit the bank and update your phone number, please press the button to allow us to put you in the record. Feel free to contact our In-App customer service once the update is completed.");
				}
			}
			if("Real name check failed (by bvn). ".equals(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("ACCOUNT and BVN do not match");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Please check your account is bound with your BVN. You may have to visit the bank to update the relevant profile and try again. If you are willing to visit the bank and update your bank account, please press the button to allow us to put you in the record. Feel free to contact our In-App customer service once the update is completed.");
				}
			}
			if("Real name check failed (By name). ".equals(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("The NAME information filled in by the user does not match the name information reserved by BVN");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Please double-check with the bank before you fill in the your name and confirm that the name you filled in is consistent with the information submitted by the bank.");
				}
			}
			if("Network abnormal, By Gps.".equals(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("GPS can't resolve");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Your verification failed due to a network issue; please try again in a place with a better and strong network.");
				}
			}
			if("Verification failed".equals(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("No information was obtained");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Your verification failed due to a network issue; please try again in a place with a better and strong network.");
				}
			}
			if("The bank BVN is inconsistent with the account number".equals(realNameAuthLog.getErrorMsg())){
				realNameAuthLog.setBehavior("ACCOUNT and BVN do not match");
				if(checkMatchingScript()){
					realNameAuthLog.setDictate("Please check your account is bound with your BVN. You may have to visit the bank to update the relevant profile and try again. If you are willing to visit the bank and update your bank account, please press the button to allow us to put you in the record. Feel free to contact our In-App customer service once the update is completed.");
				}
			}
		}
	}


	/**
	 * 根据cust_no查询出来授信申请记录
	 */
	@Log(title = "查询授信申请记录")
	@GetMapping("/findcreditlist/bycustno")
	public TableDataInfo findCreditListByCustNo(CreditApply creditapp) {
		startPage();
		String custNo = creditapp.getCustNo();
		List<CreditApplyRsp> creditApplyLists = customerService.findCreditListByCustNo(custNo);
		CustomerRsp peopleInfo = getPeopleInfo(custNo);
		String clientName = "";
		if(null != peopleInfo){
			clientName=peopleInfo.getClientName();
		}
		if(CollectionUtils.isEmpty(creditApplyLists)){
			return getDataTable(creditApplyLists);
		}
		for (CreditApplyRsp creditApplyList: creditApplyLists) {
			// 细化授信失败，匹配话术
			// 提现拒绝的状态，如果描述是规则拒绝，就是风控规则被拒，如果描述不是规则拒绝，就非风控规则失败
			if( APPLY_STATE_REJECT == creditApplyList.getApplyStatus() && "Rule reject".equals(creditApplyList.getRemark())){
				creditApplyList.setBehavior("Not eligible to apply");
				creditApplyList.setDictate("Dear " +
						clientName +
						", unfortunately, your credit application has been declined due to your credit record does not meet our loan requirements. We truly apologize for bringing you an unpleasant experience. Please keep a good credit history and come back to apply after the stipulated time given. Thanks");
			}
			if(APPLY_STATE_REJECT == creditApplyList.getApplyStatus() && !"Rule reject".equals(creditApplyList.getRemark())){
				creditApplyList.setBehavior("Reapply for credit application");
				creditApplyList.setDictate("Dear " +
						clientName +
						", your credit application has been canceled. Please upgrade the app to the latest version on the Google play store and apply again. We are deeply sorry for the inconvenience.");
			}
		}
		return getDataTable(creditApplyLists);
	}

	/**
	 * 	发送催收短信
	 * @param sendCollectSMSReq
	 */
	@GetMapping(value = "/sendcollectsms")
	public AjaxResult sendCollectSMS(SendCollectSMSReq sendCollectSMSReq){
		//查询还款VA账号
		MonnifyReservedAccount monnifyReservedAccount = customerService.getVaReservedAccount(sendCollectSMSReq.getCustNo());
		if (monnifyReservedAccount == null) {
			return AjaxResult.error();
		}
		//查询 lastName
		RealNameAuth realNameAuth = realNameAuthService.getOne(new QueryWrapper<RealNameAuth>().eq("cust_no", sendCollectSMSReq.getCustNo()).select("last_name", "user_id").last("limit 1"));
		//查询注册手机号
		AppUser appUser = appUserService.getOne(new QueryWrapper<AppUser>().eq("user_uuid", realNameAuth.getUserId()).select("phone").last("limit 1"));
		//获取短信发送次数
		try {
			String result = getSmsSendCount(appUser.getPhone());
			JSONObject json = JSONObject.parseObject(result);
			if (json.containsKey("data") && json.getJSONObject("data").getInteger("logSize") >= 3) {
				return AjaxResult.error("The number of sending times exceeded the limit");
			}
		} catch (Exception e) {
			logger.error("-----查询短信发送次数失败：", e);
		}
		//组装信息
		JSONObject param = new JSONObject();
		param.put("lastName", realNameAuth.getLastName());
		param.put("accountNumber", monnifyReservedAccount.getAccountNumber());
		param.put("bank", monnifyReservedAccount.getBankName());
		SmsSendData smsData = SmsSendData.builder().smsType("repayment_account").noticeType("collect").countryCode("+234").phoneNumber(appUser.getPhone()).smsParam(param).build();
		smsService.sendSms(smsData);
		return AjaxResult.success();
	}

	/**
	 * 获取短信发送次数
	 * @param register
	 * @return
	 */
	private String getSmsSendCount(String register) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//查询短信服务获取发送记录
		JSONObject jsonObject = smsSignUtil.encryptBASE64();
		JSONObject data = new JSONObject();
		data.put("phoneNumber",register);
		data.put("createTime",sdf.format(new Date()));
		data.put("smsType","repayment_account");
		jsonObject.put("data",data);
		//接口响应结果
		String result = "";
		try {
			result = smsUtil.sendPost(smsSendConfig.getSmsSendInfoUrl(),jsonObject, null);
		} catch (Exception e) {
			throw new BusinessException(RspEnmu.SMS_SEND_INFO_GET_FAILED);
		}
		return result;
	}

	/**
	 * 延期产品offer
	 * @param loanDeferredOrder
	 * @return
	 */
	@GetMapping("/deferredInfo")
	public AjaxResult deferredInfo(LoanDeferredOrder loanDeferredOrder) {
		return AjaxResult.success(customerService.selectdeferredInfo(loanDeferredOrder));
	}

	/**
	 * 查询用户借据延期记录order列表
	 */
	@GetMapping("/loanDeferredOrderFunList")
	public TableDataInfo loanDeferredOrderFunList(LoanDeferredOrder loanDeferredOrder) {
		startPage();
		List<LoanDeferredOrderVo> list = customerService.selectLoanDeferredOrderFunList(loanDeferredOrder);
		return getDataTable(list);
	}


	/**
	 * 查询钱包明细
	 * @param walletAmount
	 * @return
	 */
	@GetMapping("/walletLisDetail")
	public AjaxResult walletListDetail(WalletAmount walletAmount) {
		return AjaxResult.success(walletAmountService.selectWalletLisDetail(walletAmount));
	}


	/**
	 * 查询钱包流水列表
	 */
	@GetMapping("/walletInfo")
	public TableDataInfo walletInfo(String custNo) {
		startPage();
		List<WalletFlowVo> list = walletFlowService.selectWalletInfoList(custNo);
		return getDataTable(list);
	}


	/**
	 * 钱包订单记录
	 * @param walletOrder
	 * @return
	 */
	@GetMapping("/walletList")
	public TableDataInfo walletList(WalletOrder walletOrder) {
		startPage();
		List<WalletOrderVo> list = walletOrderService.selectWalletList(walletOrder);
		return getDataTable(list);
	}

}
